<template>
    <div class="login-container">
        <h2>登录</h2>
        <input type="text" v-model="username" placeholder="请输入用户名" />
        <input type="password" v-model="password" placeholder="请输入密码" />
        <button @click="handleLogin">登录</button>
        <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
    </div>
</template>

<script>
import { ref } from 'vue';
import { loginApi } from '../api/user';

export default {
    name: 'LoginComponent',
    setup(props, { emit }) {
        const username = ref('');
        const password = ref('');
        const errorMessage = ref('');

        const handleLogin = async () => {
            if (!username.value.trim() || !password.value.trim()) {
                errorMessage.value = '用户名和密码不能为空';
                return;
            }

            try {
                const result = await loginApi(username.value, password.value);
                result.fromName = username.value;
                if (result.is_system) {
                    emit('login-success', result);
                    errorMessage.value = '';
                } else {
                    errorMessage.value = result.message || '登录失败';
                }
            } catch (error) {
                errorMessage.value = '网络错误，请稍后再试';
                console.error('Login error:', error);
            }
        };
        console.log("handlelogin:" + handleLogin);
        return {
            username,
            password,
            errorMessage,
            handleLogin
        };
    }
};
</script>

<style scoped>
.login-container {
    max-width: 300px;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.login-container input {
    display: block;
    width: 100%;
    margin-bottom: 10px;
    padding: 8px;
    box-sizing: border-box;
}

.login-container button {
    width: 100%;
    padding: 10px;
    background-color: #42b983;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

.error {
    color: red;
    margin-top: 10px;
}
</style>
